/*jslint windows: true, browser: true */
/*globals window */
var APP = function () {
  var start = 0;
  var count_down = 0;
  var last_time = count_down;
  var count_down_interval = 0;
  var intervalId = 0;
  var blinkId = -1;
  var running = false;
  var beepCounter = 0;
  System.Gadget.settingsUI = "stopwatchsettings.html";

  var showTime = function (now) {
    var hour = Math.floor((now / 3600000) % 24);
    var min = Math.floor((now / 60000) % 60);
    var sec = Math.floor((now / 1000) % 60);
    var tenths = Math.floor((now / 100) % 10);
    if (min < 10) { min = "0" + min; }
    if (sec < 10) { sec = "0" + sec; }
    if (hour < 10) { hour = "0" + hour; }
    document.getElementById("watch").firstChild.nodeValue = hour + ":" + min + ":" + sec + "." + tenths;
  };

  var setCountDown = function (decrement) {
    count_down += (decrement ? -count_down_interval : count_down_interval);
    last_time = count_down;
    showTime(count_down);
  };

  var reset = function () {
    var event = window.event;
    if (event !== null && event.shiftKey === 1) {
      setCountDown();
      return;
    }
    if (intervalId !== -1) { clearInterval(intervalId); }
    intervalId = -1;
    if (blinkId !== -1) { clearInterval(blinkId); }
    count_down_interval = parseInt(System.Gadget.Settings.readString("interval"), 10);
    if (isNaN(count_down_interval)) { count_down_interval = 30000; }
    blinkId = -1;
    start = 0;
    last_time = 0;
    count_down = 0;
    running = false;
    beepCounter = 0;
    document.getElementById("watch").style.visibility = "";
    showTime(0);
  };

  var blink = function () {
    var watch = document.getElementById("watch");
    watch.style.visibility = (watch.style.visibility == "hidden") ? "" : "hidden";
    beepCounter += 1;
    if (beepCounter < 10) { System.Sound.playSound("beep.wav"); }
  };

  var ticker = function () {
    last_time = (count_down > 0) ? start - (new Date()).getTime() : (new Date()).getTime() - start;
    if (last_time <= 0) {
      reset();
      blinkId = setInterval(blink, 1000);
    }
    showTime(last_time);
  };

  var startstop = function () {
    if (blinkId != -1) {
      reset();
    }
    else if (running) {
      clearInterval(intervalId);
      running = false;
    }
    else if (window.event.shiftKey == 1) {
      setCountDown(event.ctrlKey == 1);
    }
    else {
      start = (count_down > 0) ? last_time + (new Date()).getTime() : (new Date()).getTime() - last_time;
      intervalId = setInterval(ticker, 50);
      running = true;
    }
  };

  System.Gadget.onSettingsClosed = reset;
  document.body.onclick = startstop;
  document.body.ondblclick = reset;
  reset();
};